<template>
  <el-container class="center-container">
    <el-form :model="userInfo" label-width="80px" class="user-info-form">
      <el-form-item label="用户名">
        <el-input v-model="userInfo.userName" disabled></el-input>
      </el-form-item>
      <el-form-item label="真实姓名">
        <el-input v-model="userInfo.name"></el-input>
      </el-form-item>
      <el-form-item label="电话号码">
        <el-input v-model="userInfo.tel"></el-input>
      </el-form-item>
      <el-form-item label="身份证">
        <el-input v-model="userInfo.sfID"></el-input>
      </el-form-item>
      <el-form-item label="头像">
        <div class="avatar-upload">
          <el-avatar :src="avatarUrl" size="100"></el-avatar>
          <el-upload
              class="avatar-uploader"
              action=""
              :http-request="uploadAvatarHandler"
              :show-file-list="false"
              :on-success="onAvatarUploadSuccess"
              :on-error="onAvatarUploadError"
          >
            <el-button size="small" type="primary">上传头像</el-button>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateUserInfo">保存修改</el-button>
        <el-button type="danger" @click="resetPasswordDialog = true">重置密码</el-button>
      </el-form-item>
    </el-form>

    <el-dialog title="重置密码" v-model="resetPasswordDialog">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef">
        <el-form-item label="新密码" prop="newPassword">
          <el-input type="password" v-model="passwordForm.newPassword"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input type="password" v-model="passwordForm.confirmPassword"></el-input>
        </el-form-item>
      </el-form>
      <!-- eslint-disable-next-line -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="resetPassword">确认</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getUserById, updateUser } from '@/api/user';
import { uploadAvatar, getUserAvatar } from '@/api/ufile';

const userInfo = reactive({
  id: null,
  userName: '',
  name: '',
  tel: '',
  sfID: '',
  money: 0,
  points: 0,
  sex: ''
});

const avatarUrl = ref('');
const resetPasswordDialog = ref(false);
const passwordForm = reactive({
  newPassword: '',
  confirmPassword: ''
});
const passwordFormRef = ref(null);
const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      }, trigger: 'blur' }
  ]
};

const userInfoString = localStorage.getItem('userInfo');
const user = JSON.parse(userInfoString);
const userId = user.id;

const loadUserInfo = async () => {
  const response = await getUserById(userId);
  if (response.code === 1) {
    Object.assign(userInfo, response.data);
    loadUserAvatar();
  } else {
    console.error(response.msg);
  }
};

const updateUserInfo = async () => {
  const response = await updateUser(userInfo);
  if (response.code === 1) {
    ElMessage.success('用户信息更新成功');
  } else {
    ElMessage.error(response.msg);
  }
};

const resetPassword = () => {
  passwordFormRef.value.validate((valid) => {
    if (valid) {
      if (passwordForm.newPassword === userInfo.password) {
        ElMessage.error('新密码不能与原密码相同');
        return;
      }
      userInfo.password = passwordForm.newPassword;
      updateUserInfo();
      resetPasswordDialog.value = false;
    }
  });
};

const onAvatarUploadError = () => {
  ElMessage.error('头像上传失败');
};

const onAvatarUploadSuccess = (response) => {
  console.log("头像上传成功");
  console.log(response);
  ElMessage.success('头像上传成功');
  loadUserAvatar(); // 上传成功后重新加载头像
};

const uploadAvatarHandler = async ({ file }) => {
  const formData = new FormData();
  formData.append('file', file);
  try {
    const response = await uploadAvatar(formData, userInfo.id); // 确保传入 userInfo.id 作为 uid
    avatarUrl.value = response.data; // 假设后端返回的是 /avatar/<filename> 的路径
    ElMessage.success('头像上传成功');
    await loadUserAvatar(); // 在头像上传成功后重新加载用户头像
    localStorage.setItem('userAvatar',avatarUrl.value);
  } catch (error) {
    ElMessage.error('头像上传失败，请重试');
    console.error('Upload error:', error);
  }
};

const loadUserAvatar = async () => {
  try {
    const response = await getUserAvatar(userId);
    console.log("我是loadUserAvatar");
    console.log(response.data.avatar_url);
    avatarUrl.value = response.data.avatar_url;
    // 添加时间戳以避免浏览器缓存
    avatarUrl.value = `${response.data.avatar_url}?t=${Date.now()}`;
  } catch (error) {
    console.error('加载用户头像失败:', error);
  }
};

onMounted(() => {
  loadUserInfo();
});
</script>

<style scoped>
.center-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  padding: 20px;
  background-color: #f9f9f9;
  width: 100%;
  height: 100vh;
}

.user-info-form {
  width: 400px;
  max-width: 100%;
}

.dialog-footer {
  text-align: right;
}

.avatar-upload {
  display: flex;
  align-items: center;
  gap: 20px;
}
</style>
